package com.atguigu.gulimall.order.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ming
 * @create 2022/5/7
 * @description:
 */
@Slf4j
@Configuration
public class MyRabbitMqConfig {
    
    private RabbitTemplate rabbitTemplate;
    //public MyRabbitMqConfig(RabbitTemplate rabbitTemplate){
    //    this.rabbitTemplate = rabbitTemplate;
    //    initRabbitTemplate();
    //}
    @Bean
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     * 1、服务收到消息就会回调
     *      1、spring.rabbitmq.publisher-confirms: true
     *      2、设置确认回调
     * 2、消息正确抵达队列就会进行回调
     *      1、spring.rabbitmq.publisher-returns: true
     *         spring.rabbitmq.template.mandatory: true
     *      2、设置确认回调ReturnCallback
     *
     * 3、消费端确认(保证每个消息都被正确消费，此时才可以broker删除这个消息)
     *
     */
    // @PostConstruct  //MyRabbitConfig对象创建完成以后，执行这个方法
    public void initRabbitTemplate() {

        /**
         * 1、只要消息抵达Broker就ack=true
         * correlationData：当前消息的唯一关联数据(这个是消息的唯一id)
         * ack：消息是否成功收到
         * cause：失败的原因
         */
        //设置确认回调
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause) -> {
            //服务器收到了  修改数据库中消息的状态
            //如果报错了,修改消息的状态->错误 
            System.out.println("confirm...correlationData["+correlationData+"]==>ack:["+ack+"]==>cause:["+cause+"]");
        });


        /**
         * 只要消息没有投递给指定的队列，就触发这个失败回调
         * message：投递失败的消息详细信息
         * replyCode：回复的状态码
         * replyText：回复的文本内容
         * exchange：当时这个消息发给哪个交换机
         * routingKey：当时这个消息用哪个路邮键
         */
        rabbitTemplate.setReturnCallback((message,replyCode,replyText,exchange,routingKey) -> {
            System.out.println("Fail Message["+message+"]==>replyCode["+replyCode+"]" +
                    "==>replyText["+replyText+"]==>exchange["+exchange+"]==>routingKey["+routingKey+"]");
        });
    }

    /**
     * 容器中的组件 bingding queue exchange 如果没有spring会帮我们创建
     * @return
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String,Object> parameters = new HashMap<String,Object>();
        parameters.put("x-dead-letter-exchange","order-event-exchange");
        parameters.put("x-dead-letter-routing-key", "order.release.order");
        parameters.put("x-message-ttl", 60000);
        Queue queue = new Queue("order.delay.queue", true, false, false,parameters);
        return queue;
    }
    @Bean
    public Queue orderReleaseOrderQueue() {
        Queue queue = new Queue("order.release.queue", true, false, false);
        return queue;
    }
    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange("order-event-exchange", true, false);
    }
    @Bean
    public Binding orderCreateOrderBinding() {
      return new Binding("order.delay.queue",
              Binding.DestinationType.QUEUE,"order-event-exchange",
              "order.create.order",null) ;
    }
    @Bean
    public Binding orderReleaseOrder(){
        return new Binding("order.release.queue",
                Binding.DestinationType.QUEUE,"order-event-exchange",
                "order.release.order",null) ;
    }

    /**
     * 订单释放直接绑定库存
     * @return
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.release.other.#", null);
    }
    @Bean
    public Queue OrderSeckillQueu(){
      return new Queue("order.seckill.order.queue",true,false,false);
    }
    @Bean
    public Binding orderSeckillQueueBinding() {
        return new Binding("order.seckill.order.queue",
                Binding.DestinationType.QUEUE, "order-event-exchange",
                "order.seckill.order", null);
    }

    
}
